﻿using Castle.DynamicProxy;
using Sapit.Base;
using Sapit.Helpers;
using Sapit.Windsor.Attributes;


namespace Sapit.Windsor
{
    public class CacheInterceptor<T> : CacheBase<T>, IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            Invocation inv = new Invocation() { InvocationTarget = invocation.InvocationTarget, Method = invocation.Method };

            var cache = AttributeHelper.GetAttributeIfPresent<CacheAttribute>(invocation.Method);
            if (cache != null)
            {
                if (IsInvocationValidInCache(inv, cache.CacheSeconds))
                {
                    invocation.ReturnValue = GetCachedValue(inv);
                }
                else
                {
                    invocation.Proceed();
                    CacheInvocationValue(inv, (T)invocation.ReturnValue);
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
